<?php

namespace app\models;

use think\Db;
use think\Model;

class User extends Model
{
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'created';
    protected $defaultSoftDelete = 0;

    /**
     * 修改币种记录
     * @param $user_id   // 用户
     * @param $comeuser_id   // 来源ID
     * @param $befores   // 变化前资产
     * @param $money   // 变化金额
     * @param $cointype   // 资产类型 1pdb  2kcb 3quota 4assets 5power
     * @param $handfee   // 手续费
     * @param $type   // 变化类型
     * @param $info   //备注
     * @param $source   // 资产来源ID
     * @param $algebra   // 收益来源代数
     * @return void
     */
    public static function MoneyEdit($user_id = 0, $befores = 0, $money = 0, $cointype = 0, $type = 0, $info = '', $source = 0, $comeuser_id = 0, $handfee = 0, $algebra = 0, $income = 0)
    {
        $res = false;
        if ($cointype == 1) {
            $res = (new User())->where(['id' => $user_id, 'money' => $befores])->setInc('money', $money);
        }
        if ($cointype == 2) {
            $res = (new User())->where(['id' => $user_id, 'amount' => $befores])->setInc('amount', $money);
        }
        if ($cointype == 3) {
            $res = (new User())->where(['id' => $user_id, 'quota' => $befores])->setInc('quota', $money);
        }
        if ($cointype == 4) {
            $res = (new User())->where(['id' => $user_id, 'assets' => $befores])->setInc('assets', $money);
        }
        if ($cointype == 5) {
            $res = (new User())->where(['id' => $user_id, 'power' => $befores])->setInc('power', $money);
        }
        $res2 = (new Moneylog())->insert([
            'logid' => time(),
            'user_id' => $user_id,
            'comeuser_id' => $comeuser_id,
            'befores' => $befores,
            'money' => $money,
            'after' => ($befores + $money),
            'cointype' => $cointype,
            'type' => $type,
            'info' => $info,
            'source' => $source,
            'handfee' => $handfee,
            'algebra' => $algebra,
            'dates' => date('Y-m-d')
        ]);
        if ($cointype == 4 && $income != 0) {
            $res3 = (new User())->where(['id' => $user_id])->setInc('allincome', $income);
            if (!$res3) {
                throw new \Exception("收益累计失败，请重试", 100);
            }
        }
        if (!$res || !$res2) {
            throw new \Exception("币种资产扣除失败，请重试", 100);
        }
    }
}
